package com.example.zjsr.controller;

import com.alibaba.excel.util.StringUtils;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.domain.*;
import com.example.zjsr.service.ExcelService;
import com.example.zjsr.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * 下载模板导入数据表
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/excel")
public class ExcelController {

    @Autowired
    public ExcelService excelService;

    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private FileUploadAndDownload fileUploadAndDownload;

    private Logger log= LoggerFactory.getLogger(ExcelController.class);


    /**
     * 下载主播信息导入模板
     * @param response
     */
    @RequestMapping(value = "/uploadAnchors",method = RequestMethod.GET)
    public void uploadAnchors(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            List<ExcelAnchors> excelAnchorsList=new ArrayList<>();
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "主播总表信息模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelAnchors excelAnchors=new ExcelAnchors();
            excelAnchors.setAnchorName("薇娅viya");
            excelAnchors.setAnchorID("69226163");
            excelAnchors.setHeadPortrait("https://img.alicdn.com/imgextra/i2/69226163/TB2YEitX3aTBuNjSszfXXXgfpXa_!!69226163-0-beehive-scenes.jpg");
            excelAnchors.setFansNumber("38,470,000");
            excelAnchors.setTodayLiveShow(1);
            excelAnchors.setLastLiveShow(22);
            excelAnchors.setLastLiveView("401,976,639");
            excelAnchors.setYestLiveAvg("678.93元");
            excelAnchors.setYestBargainAvg("402.32元");
            excelAnchors.setYestLiveQuantity("1,270,411");
            excelAnchors.setYestLiveSales("511,117,077元");
            excelAnchors.setWhetherV("否");
            excelAnchors.setSyntheticAbility("789分");
            excelAnchors.setServiceScore("5分");
            excelAnchorsList.add(excelAnchors);
            ExcelUtils.writeExcel(out, ExcelAnchors.class,excelAnchorsList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载主播直播信息导入模板（）
     * @param response
     */
    @RequestMapping(value = "/uploadAnchorsInfo",method = RequestMethod.GET)
    public void uploadAnchorsInfo(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            List<ExcelAnchorsInfo> excelAnchorsInfoList=new ArrayList<>();
            ExcelAnchorsInfo excelAnchorsInfo=new ExcelAnchorsInfo();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "主播详细信息模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            excelAnchorsInfo.setInfoName("薇娅viya");
            excelAnchorsInfo.setInfoAnchorID("69226163");
            excelAnchorsInfo.setInfoHeadPortrait("https://p3-dy-ipv6.byteimg.com/aweme/1080x1080/3142600033073e09eb2ea.webp?from=2956013663");
            excelAnchorsInfo.setInfoDate("2020-12-10");
            excelAnchorsInfo.setInfoFansNumber("38,470,000");
            excelAnchorsInfo.setBeginDate("20:00");
            excelAnchorsInfo.setEndDate("24:30");
            excelAnchorsInfo.setLiveEvents(1);
            excelAnchorsInfo.setViewNums("31,942,188");
            excelAnchorsInfo.setTreasureAvg("678.93元");
            excelAnchorsInfo.setTreasureBargainAvg("402.32元");
            excelAnchorsInfo.setSalesVolume("1,270,411");
            excelAnchorsInfo.setSales("511,117,077元");
            excelAnchorsInfoList.add(excelAnchorsInfo);
            ExcelUtils.writeExcel(out, ExcelAnchorsInfo.class,excelAnchorsInfoList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 下载水果总类导入模板
     * @param response
     */
    @RequestMapping(value = "/uploadFruit",method = RequestMethod.GET)
    public void uploadFruit(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "水果总类信息模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            List<ExcelFruit> excelFruitList=new ArrayList<>();
            ExcelFruit excelFruit=new ExcelFruit();
            excelFruit.setFruitId(1);
            excelFruit.setTitle("山东水蜜桃金秋红蜜桃水果新鲜冬桃大桃子当季10整箱金秋蜜桃脆斤");
            excelFruit.setPictureLink("https://img.alicdn.com/imgextra/i2/129789293/O1CN01BUr0fO2IWFHDxqvcy_!!0-saturn_solar.jpg_400x400.jpg");
            excelFruit.setSale("27.8");
            excelFruit.setInventory(336325);
            excelFruit.setTotalSales("140599");
            excelFruit.setGrossSales("6087936.7");
            excelFruit.setCollection("36660");
            excelFruit.setEvaluationSeveral("34632");
            excelFruit.setSalesVolume("30000，31000，32000，25000，24000，22000，23000，24000，26000，29000，31000，32000");
            excelFruit.setPrice("26.9，27.9，29.8，30.9，29.9，27.8，29.8，31.8，31.9，26.5，24.9，25.8");
            excelFruit.setScore("5.0，4.9，5.0，4.8，4.7，4.8，4.8，4.9，5.0，5.0，5.0，4.9");
            excelFruit.setInventoryData("300000，310000，320000，250000，240000，220000，230000，240000，260000，290000，310000，320000");
            excelFruit.setNetContent("1500g 2500g 4500g");
            excelFruit.setProvince("山东");
            excelFruit.setAddress("http://item.taobao.com/item.htm?id=604581029445");
            excelFruit.setEvaluationLabel("口感不错(2752) ; 新鲜(1267) ; 味道不错(705) ; 包装很好(652) ; 个头大(499) ; 不太新鲜(647) ;");
            excelFruitList.add(excelFruit);
            ExcelUtils.writeExcel(out, ExcelFruit.class,excelFruitList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载水果总类数据信息
     * @param response
     */
    @RequestMapping(value = "/downloadFruit",method = RequestMethod.GET)
    public void downloadFruit(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "水果总类数据信息";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            List<ExcelFruit> excelFruitList=excelService.downloadFruit();
            ExcelUtils.writeExcel(out, ExcelFruit.class,excelFruitList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载水果详细信息导入模板
     * @param response
     */
    @RequestMapping(value = "/uploadFruitInfo",method = RequestMethod.GET)
    public void uploadFruitInfo(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "水果详细信息模板";
            List<ExcelFruitInfo> excelFruitInfoList=new ArrayList<>();
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelFruitInfo excelFruitInfo=new ExcelFruitInfo();
            excelFruitInfo.setTitle("云南大理冬桃新鲜10斤脆桃整箱当季时令水果现摘现发蜜桃子毛桃");
            excelFruitInfo.setPictureMap("https://img.alicdn.com/imgextra/i3/420980009/O1CN01AD68Ar1BwACsuth84_!!0-saturn_solar.jpg_400x400.jpg");
            excelFruitInfo.setLowSales(17.8);
            excelFruitInfo.setInventory(289877);
            excelFruitInfo.setPostage("0");
            excelFruitInfo.setTotalSales(125);
            excelFruitInfo.setGrossSales("13500");
            excelFruitInfo.setThirtyDaysSales("15");
            excelFruitInfo.setSalesAccounted("0.02%");
            excelFruitInfo.setThirtyDaysSaleroom("1620");
            excelFruitInfo.setSaleroom("0.05%");
            excelFruitInfo.setCollection("40");
            excelFruitInfo.setEvaluationSeveral("20");
            excelFruitInfo.setPlaceDispatch("上海");
            excelFruitInfo.setFavorableRate("100.00%");
            excelFruitInfo.setSellingTime("8月 9月 10月 11月 12月");
            excelFruitInfo.setNetContent("2.5kg(含）-5kg(不含)");
            excelFruitInfo.setSellingWay("见包装");
            excelFruitInfo.setCity("凉山彝族自治州");
            excelFruitInfo.setMannerPacking("四川");
            excelFruitInfo.setDistFre("1周2次");
            excelFruitInfo.setProvince("陕西");
            excelFruitInfo.setPackageWeight("3人份");
            excelFruitInfo.setSetCycle("1周");
            excelFruitInfo.setAge("25-35");
            excelFruitInfo.setSex("男");
            excelFruitInfo.setCharacters("小巧圆润 ; 脆甜离核 ; 甜蜜多汁 ; 果形小巧 ; 红润饱满 ; 核小肉厚 ; 果肉细腻 ; 果味浓郁 ;");
            excelFruitInfo.setFreshStorageTemp("0-8℃");
            excelFruitInfo.setPrice("0-50元");
            excelFruitInfo.setEvaluationLabel("口感不错(23) ; 包装很好(7) ; 新鲜(7) ; 个头大(4) ; 物流快(4) ; 口感一般(6) ;");
            excelFruitInfoList.add(excelFruitInfo);
            ExcelUtils.writeExcel(out, ExcelFruitInfo.class,excelFruitInfoList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 上传所有主播信息
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/leadAnchors",method = RequestMethod.POST)
    public ServerResponse leadAnchors(MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        List<Anchors> anchorsList = new ArrayList<>();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, Anchors.class);
            if (objectList == null) {
                log.info("数据有误");
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                log.info("空");
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    Anchors  anchors= (Anchors) objectList.get(i);
                    anchorsList.add(anchors);
                }
                //上传完成 删除临时文件
                tmpFile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return excelService.leadAnchors(anchorsList);
    }


    /**
     * 导入主播直播场次信息
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/leadAnchorsInfo",method = RequestMethod.POST)
    public ServerResponse leadAnchorsInfo(MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        List<AnchorsInfo> anchorsInfoList = new ArrayList<>();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, AnchorsInfo.class);
            if (objectList == null) {
                log.info("数据有误");
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                log.info("空");
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    AnchorsInfo  anchorsInfo= (AnchorsInfo) objectList.get(i);
                    anchorsInfoList.add(anchorsInfo);
                }
                //上传完成 删除临时文件
                tmpFile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return excelService.leadAnchorsInfo(anchorsInfoList);
    }


    /**
     * 上传水果种类信息
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/leadFruit",method = RequestMethod.POST)
    public ServerResponse leadFruit(MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        List<ExcelFruit> excelFruitArrayList = new ArrayList<>();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, ExcelFruit.class);
            if (objectList == null) {
                log.info("数据有误");
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                log.info("空");
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    ExcelFruit  excelFruit= (ExcelFruit) objectList.get(i);
                    if(StringUtils.isEmpty(excelFruit.getFruitId())){
                        return ServerResponse.createByErrorMsg("水果种类编号不能为空！");
                    }else{
                        excelFruitArrayList.add(excelFruit);
                    }
                }
                //上传完成 删除临时文件
                tmpFile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return excelService.leadFruit(excelFruitArrayList);
    }


    /**
     * 导入水果详细信息
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/leadFruitInfo",method = RequestMethod.POST)
    public ServerResponse leadFruitInfo(MultipartFile file, HttpServletRequest request,Integer fruitId){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
//        Integer fruitId=0;
//        try {
//            fruitId= Integer.valueOf(fileName.substring(0,fileName.indexOf(".")));
//        } catch (NumberFormatException e) {
//            log.error("{}上传文件名没有按照规定的来",fileName);
//            e.printStackTrace();
//            return ServerResponse.createByErrorMsg("上传文件名没有按照规定的来");
//        }
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为：" + suffixName);
        //创建一个临时文件，用于暂时存放
        List<ExcelFruitInfo> excelFruitInfoArrayList = new ArrayList<>();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            List<Object> objectList = ExcelUtils.readExcel(inputStream, ExcelFruitInfo.class);
            if (objectList == null) {
                log.info("数据有误");
                return ServerResponse.createByErrorMsg("数据有误，上传失败");
            } else if (EmptyUtil.isEmpty(objectList)) {
                log.info("空");
                return ServerResponse.createByErrorMsg("数据为空");
            } else {
                for (int i = 0; i < objectList.size(); i++) {
                    ExcelFruitInfo  excelFruitInfo= (ExcelFruitInfo) objectList.get(i);
                    excelFruitInfo.setFruitId(fruitId);
                    excelFruitInfoArrayList.add(excelFruitInfo);
                }
                //上传完成 删除临时文件
                tmpFile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return excelService.leadFruitInfo(excelFruitInfoArrayList,fruitId);
    }


    /**
     * 根据水果总类编号来上传图片
     * @param fruitId
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadFruitPicture",method = RequestMethod.POST)
    public ServerResponse uploadFruitPicture(HttpServletRequest request,Integer fruitId,MultipartFile file){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
  /*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String path="";
        try {
            path=fileUploadAndDownload.upload(file);
            if(null==path){
                return ServerResponse.createBySuccessMsg("上传图片失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createBySuccessMsg("上传图片失败");
        }
        return excelService.uploadFruitPicture(fruitId,path);
    }
}
